
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from database import get_db

from models.department_model import Department
from schemas.department_schemas import DepartmentCreate, DepartmentUpdate
from services.user_service import get_all_users, get_user, create_user, delete_user, update_user
from models.user_models import UserType
from services.auth_service import require_user

router = APIRouter()

@router.get("/departments")
def get_departments(db: Session = Depends(get_db), user=Depends(require_user(UserType.ADMIN))):
    # We reuse the get_all_users function but specify a dummy UserType
    # Since Department isn't a user type, we'll just query directly here
    try:
        departments = db.query(Department).all()
        return departments
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/departments/{department_id}")
def get_department(department_id: int, db: Session = Depends(get_db), 
                  user=Depends(require_user(UserType.ADMIN))):
    try:
        department = db.query(Department).filter_by(ID=department_id).first()
        if department is None:
            raise HTTPException(status_code=404, detail="Department not found")
        return department
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/departments")
def create_department(department: DepartmentCreate, db: Session = Depends(get_db),
                     user=Depends(require_user(UserType.ADMIN))):
    try:
        department.check()
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))

    try:
        db_department = Department.from_dict(department.model_dump())
        db.add(db_department)
        db.commit()
        db.refresh(db_department)
        return {
            "message": "Department created successfully!",
            "department": db_department.to_dict()
        }
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=400, detail=str(e))

@router.delete("/departments/{department_id}")
def delete_department(department_id: int, db: Session = Depends(get_db),
                     user=Depends(require_user(UserType.ADMIN))):
    try:
        department = db.query(Department).filter_by(ID=department_id).first()
        if not department:
            raise HTTPException(status_code=404, detail="Department not found")
        
        db.delete(department)
        db.commit()
        return {"message": "Department deleted successfully!"}
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=400, detail=str(e))

@router.put("/departments/{department_id}")
def update_department(department_id: int, department_update: DepartmentUpdate, 
                     db: Session = Depends(get_db),
                     user=Depends(require_user(UserType.ADMIN))):
    try:
        department_update.check()
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))

    try:
        department = db.query(Department).filter_by(ID=department_id).first()
        if not department:
            raise HTTPException(status_code=404, detail="Department not found")

        update_data = department_update.model_dump(exclude_unset=True)
        for key, value in update_data.items():
            setattr(department, key, value)

        db.commit()
        db.refresh(department)
        return {
            "message": "Department updated successfully!",
            "department": department.to_dict()
        }
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=400, detail=str(e))